package com.hengxinguotong.zhihuichengjian.ui.security;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.SafetyListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Safety;
import com.hengxinguotong.zhihuichengjian.bean.SafetyListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 安全培训 安全演习列表
 * Created by liux on 2017/3/15.
 */

public class SafetyListActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.safety_lv)
    PullToRefreshListView safetyLv;
    @BindView(R.id.add)
    HXTextView add;
    private int pageIndex = 1;
    private int type = 1;
    private List<Safety> safeties;
    private SafetyListAdapter safetyListAdapter;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_safetylist);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 1);
        if (type == 1) {
            titleTv.setText("安全培训列表");
        } else {
            titleTv.setText("安全演习列表");
        }

        if(hasAdd()){
            add.setVisibility(View.VISIBLE);
        }

        safetyLv.setMode(PullToRefreshBase.Mode.BOTH);
        safetyLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getSafetyInfo(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getSafetyInfo(null);
            }
        });


        safetyLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Safety safety = safeties.get(position - 1);
                Intent intent = new Intent(SafetyListActivity.this, SafetyDrillActivity.class);
                intent.putExtra("safety", safety);
                intent.putExtra("type", type);
                startActivity(intent);
            }
        });
        handler.postDelayed(MyRunnable, 500);
    }

    Runnable MyRunnable = new Runnable() {
        @Override
        public void run() {
            safetyLv.setRefreshing();
        }
    };


    private void getSafetyInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
            jsonObject.put("pageNum", pageIndex);
            jsonObject.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/safeStudy/queryByConstructionId/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (safetyLv.isRefreshing()) {
                    safetyLv.onRefreshComplete();
                }

                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    SafetyListRes safetyListRes = gson.fromJson(json, SafetyListRes.class);
                    addData(safetyListRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
                if (safetyLv.isRefreshing()) {
                    safetyLv.onRefreshComplete();
                }
            }
        });
    }


    private void addData(List<Safety> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(safetyLv);
            }else{
                dismissEmptyView();
            }
            safeties = datas;
            safetyListAdapter = new SafetyListAdapter(safeties, this, type);
            safetyLv.setAdapter(safetyListAdapter);
            if (datas.size() == Utils.ONCECOUNT) {
                safetyLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            safeties.addAll(datas);
            safetyListAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            safetyLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            handler.postDelayed(MyRunnable, 500);
        }
    }

    @OnClick({R.id.iv_back, R.id.add})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.add:
                intent = new Intent(this, SafetyDrillActivity.class);
                intent.putExtra("type", type);
                startActivityForResult(intent, 1);
                break;
        }
    }
}
